<script>
  import FieldLabel from "./FieldLabel.svelte";

  export let label = "";
  export let value = 0;
  export let defaultValue = 0; // 新增：默认值
  export let min = 0;
  export let max = 100;
  export let step = 1;
  export let readonly = false;
  export let disabled = false;
  export let required = false;
  export let error = "";
  export let hideError = true; // 新增：控制错误信息显示

  // 初始化时检查并设置默认值
  $: if (value === null || value === undefined) {
    value = defaultValue;
  }

  // 验证函数
  export function validate() {
    if (required && (value === null || value === undefined || value === "")) {
      error = `请输入${label}`;
      return false;
    }

    const numValue = parseFloat(value);
    if (isNaN(numValue)) {
      error = `${label}必须是有效数字`;
      return false;
    }

    if (numValue < min) {
      error = `${label}不能小于 ${min}`;
      return false;
    }

    if (numValue > max) {
      error = `${label}不能大于 ${max}`;
      return false;
    }

    error = "";
    return true;
  }

  // 清除错误
  export function clearError() {
    error = "";
  }

  // 设置错误
  export function setError(msg) {
    error = msg;
  }

  function increment() {
    const newValue = parseFloat((value + step).toFixed(getDecimalPlaces(step)));
    if (newValue <= max) {
      value = newValue;
      if (error) error = "";
    }
  }

  function decrement() {
    const newValue = parseFloat((value - step).toFixed(getDecimalPlaces(step)));
    if (newValue >= min) {
      value = newValue;
      if (error) error = "";
    }
  }

  // 处理输入事件
  function handleInput(event) {
    const inputValue = event.target.value;

    // 允许空值和负号
    if (inputValue === "" || inputValue === "-") {
      return;
    }

    const numValue = parseFloat(inputValue);

    // 检查是否是有效数字
    if (isNaN(numValue)) {
      error = `${label}必须是有效数字`;
      return;
    }

    // 实时范围检查
    if (numValue < min) {
      error = `${label}不能小于 ${min}`;
      return;
    }

    if (numValue > max) {
      error = `${label}不能大于 ${max}`;
      return;
    }

    // 清除错误
    if (error) {
      error = "";
    }
  }

  // 处理失焦事件
  function handleBlur() {
    if (value === "" || value === null || value === undefined) {
      value = defaultValue; // 设置默认值
      if (required) {
        validate();
      }
      return;
    }

    const numValue = parseFloat(value);

    // 确保值在范围内
    if (numValue < min) {
      value = min;
      error = "";
    } else if (numValue > max) {
      value = max;
      error = "";
    }

    validate();
  }

  // 获取小数位数
  function getDecimalPlaces(num) {
    const str = num.toString();
    if (str.indexOf(".") !== -1) {
      return str.split(".")[1].length;
    }
    return 0;
  }
</script>

<div class="number-field">
  <FieldLabel {label} {required} />

  {#if readonly}
    <div class="readonly-value">{value}</div>
  {:else}
    <div class="number-input-container">
      <input
        type="number"
        bind:value
        {min}
        {max}
        {step}
        {disabled}
        class="number-input"
        class:error={!!error}
        on:input={handleInput}
        on:blur={handleBlur}
      />
      <div class="number-controls">
        <button
          type="button"
          on:click={increment}
          class="control-btn increment"
          disabled={disabled || value >= max}
        >
          <svg width="10" height="10" viewBox="0 0 16 16" fill="currentColor">
            <path
              d="M8 2a.5.5 0 0 1 .5.5v5h5a.5.5 0 0 1 0 1h-5v5a.5.5 0 0 1-1 0v-5h-5a.5.5 0 0 1 0-1h5v-5A.5.5 0 0 1 8 2Z"
              stroke="currentColor"
              stroke-width="0.5"
            />
          </svg>
        </button>
        <div class="divider"></div>
        <button
          type="button"
          on:click={decrement}
          class="control-btn decrement"
          disabled={disabled || value <= min}
        >
          <svg width="10" height="10" viewBox="0 0 16 16" fill="currentColor">
            <path
              d="M2.5 7.5a.5.5 0 0 0 0 1h11a.5.5 0 0 0 0-1h-11Z"
              stroke="currentColor"
              stroke-width="0.8"
            />
          </svg>
        </button>
      </div>
    </div>
  {/if}

  {#if error && !hideError}
    <div class="field-error">{error}</div>
  {/if}

  <!-- 显示数值范围提示 -->
  <!-- <div class="field-hint">
    数值范围：{min} - {max}
  </div> -->
</div>

<style>
  .number-field {
    margin-bottom: 24px;
  }

  .number-field:last-child {
    margin-bottom: 0;
  }

  .number-input-container {
    position: relative;
    display: flex;
  }

  .number-input {
    width: 100%;
    padding: 8px 8px 8px 10px !important;
    border: 1px solid #e0e0e0;
    border-radius: 4px;
    font-size: 13px;
    box-sizing: border-box;
    background: #fff;
    color: #333;
  }

  .number-input:focus {
    outline: none;
    border-color: #1890ff;
    box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.1);
  }

  .number-input:disabled {
    background: #f5f5f5;
    color: #ccc;
    cursor: not-allowed;
  }

  .number-input.error {
    border-color: #ff4d4f;
   }

  .number-input.error:focus {
    border-color: #ff4d4f;
    box-shadow: 0 0 0 2px rgba(255, 77, 79, 0.1);
  }

  .number-controls {
    position: absolute;
    right: 1px;
    top: 1px;
    bottom: 1px;
    display: flex;
    flex-direction: column;
    width: 20px;
    background: #f8f9fa;
    border-radius: 0 3px 3px 0;
    border-left: 1px solid #e0e0e0;
  }

  .control-btn {
    flex: 1;
    border: none;
    background: transparent;
    cursor: pointer;
    color: #666;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all 0.2s;
    padding: 2px;
  }

  .control-btn:hover:not(:disabled) {
    color: rgba(69, 81, 229, 1);
  }

  .control-btn:disabled {
    color: #ccc;
    cursor: not-allowed;
  }

  .increment {
    border-radius: 0 3px 0 0;
  }

  .decrement {
    border-radius: 0 0 3px 0;
  }

  .divider {
    height: 1px;
    background: #e0e0e0;
  }

  .readonly-value {
    padding: 8px 0;
    font-size: 13px;
    color: #333;
    line-height: 1.5;
    min-height: 21px;
  }

  .field-error {
    margin-top: 4px;
    font-size: 12px;
    color: rgba(238, 70, 70, 1);
  }

  .field-hint {
    margin-top: 4px;
    font-size: 12px;
    color: #666;
  }
</style>
